using System;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging;
using Microsoft.Extensions.DependencyInjection;
using ZechatApp.Messages;
using ZechatApp.Models;
using ZechatApp.Services;

namespace ZechatApp.ViewModels;

public partial class LoginPageViewModel : ViewModelBase
{
    [ObservableProperty] [NotifyCanExecuteChangedFor(nameof(LoginCommand))]
    private string? _username;

    [ObservableProperty] [NotifyCanExecuteChangedFor(nameof(LoginCommand))]
    private string? _password;

    [ObservableProperty] private bool _isLoading;

    [ObservableProperty] private string? _errorMessage;
    [ObservableProperty] private bool _hasError;

    private readonly HttpClientService _httpClientService = App.Services?.GetRequiredService<HttpClientService>() ??
                                                            throw new Exception("HttpClientService is null");

    private bool CanLogin =>
        !string.IsNullOrWhiteSpace(Username) &&
        !string.IsNullOrWhiteSpace(Password);

    [RelayCommand(CanExecute = nameof(CanLogin))]
    private async Task LoginAsync()
    {
        IsLoading = true;

        // await _httpClientService.GetBaidu();
        var authResponse = await _httpClientService.BzAuthAsync(Username!, Password!);
            
        IsLoading = false;

        if (authResponse != null)
        {
            HasError = false;

            // (App.SendPort, App.ListenPort) = CommonService.GetFreePorts();

            // var msg = new BzMessage(authResponse.Data);

            // var exePath = Path.Combine(Directory.GetCurrentDirectory(), "tool", "dfg", "inject_tool.exe");
            // var arguments = $"start {App.SendPort} --my_port={App.ListenPort}";

            // Console.WriteLine($"Starting process: {exePath} {arguments}");

            // var outputStr = CommonService.RunInjectExe(exePath, arguments);
            // Console.WriteLine($"注入结果：{outputStr}");
            //
            // WeakReferenceMessenger.Default.Send(msg);
        }
        else
        {
            HasError = true;
            ErrorMessage = authResponse.Nickname;
        }
    }
}